<?php

use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
use common\models\goods\GoodsCategory;
use common\models\Brand;

/* @var $this yii\web\View */
/* @var $model common\models\goods\GoodsCategory */
/* @var $form yii\widgets\ActiveForm */

$routes = [];
$ids = $model->isNewRecord ? [0] : array_merge($model->route,[$model->id]);

foreach ($ids as $id) {
    $child = GoodsCategory::find()->where(['parent_id' => $id])->all();
    if ($child) {
        $ret = ArrayHelper::map($child, 'id', 'name');
        $routes[] = $ret;
    }
}

if (!$model->isNewRecord) {
    $model->brand_ids = explode(',', $model->brand_ids);
}
$brands = ArrayHelper::map(Brand::find()->all(), 'id', 'name');

?>

<div class="goods-category-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => 45]) ?>

    <div class="form-group field-region-name required">
        <label class="control-label" for="region-name">父路径</label>
        <div id="parentList">
            <?php foreach ($routes as $item): ?>
                <select name="GoodsCategory[parent_id][]" class="parent" >
                    <option value="0">不选择</option>
                    <?php foreach ($item as $id => $name): ?>
                        <?php if($model->id!=$id):?>
                        <option value="<?= $id ?>" <?php if ($model->parent_id!=0 && in_array($id, $ids)): ?>selected<?php endif; ?>><?= $name ?></option>
                        <?php endif;?>
                    <?php endforeach; ?>
                </select>
            <?php endforeach; ?>
        </div>
        <div class="help-block">如果不在当前层级，请选择 "不选择"。</div>
    </div>

    <?= $form->field($model, 'sort')->textInput() ?>
    
    <?= $form->field($model, 'brand_ids')->checkboxList($brands) ?>
    
    
    
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? '新建' : '更新', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

<script>
    window.onload = function () {
        $('.parent').bind('change', function () {
            var id = $(this).val();
            var url = '<?= yii\helpers\Url::to(['get-parent']) ?>';
            $.get(url, {id: id}, function (ret) {
                $('#parentList').html(ret);
            });
        });
    }
</script>